<template>
    <div>
        <div class="container">
            <div class="handle-box">
                <div>
                    <el-input v-model="query.keywords" placeholder="关键词" class="handle-input mr10"></el-input>
                    <el-select v-if="departs.length > 1" v-model="query.depart" class="m-2 mr10" placeholder="请选择部门"
                        size="large">
                        <el-option key="0" label="全部部门" value="0" />
                        <el-option v-for="depart in departs" :key="depart.depart_id" :label="depart.depart_name"
                            :value="depart.depart_id" />
                    </el-select>

                    <el-button type="primary" class="m-2" size="small" icon="el-icon-search"
                        @click="handleSearch">搜索</el-button>
                </div>
                <div>
                    <el-button type="primary" size="small" icon="el-icon-plus" @click="handleCreate" class="add-btn">
                        添加床位</el-button>
                </div>
            </div>
            <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header"
                :cell-style="{padding:'3px 0'}">
                <el-table-column prop="bed_id" label="ID" align="center" width="55"></el-table-column>
                <el-table-column prop="depart_name" label="病区"></el-table-column>
                <el-table-column prop="room_name" align="center" label="房间"></el-table-column>
                <el-table-column prop="bed_name" align="center" label="床号"></el-table-column>
                <el-table-column prop="screen_head_sn" align="center" label="床位屏"></el-table-column>
                <el-table-column prop="infusion_sn" align="center" label="输液器"></el-table-column>
                <el-table-column label="状态" align="center">
                    <template #default="scope">
                        <el-tag type="success" v-if="scope.row.bed_state == 1" size="small">空床</el-tag>
                        <el-tag type="info" v-if="scope.row.bed_state == 2" size="small">占用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="300" align="center">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">编辑
                        </el-button>
                        <el-button type="danger" size="small" @click="handleDelete(scope.$index, scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination background layout="total, prev, pager, next" :current-page="query.page"
                    :page-size="query.limit" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
            </div>
        </div>

        <!-- 添加弹出框 -->
        <el-dialog title="添加" v-model="addVisible" width="50%">
            <el-form label-width="110px">
                <el-form-item label="病区">
                    <el-select v-model="createForm.depart_id" class="m-2" placeholder="请选择病区" size="large">
                        <el-option v-for="item in departs" :key="item.depart_id" :label="item.depart_name"
                            :value="item.depart_id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="房间">
                    <el-select readonly v-model="createForm.room_id" class="m-2" placeholder="请选择房间" size="large">
                        <el-option v-for="item in  rooms.filter(v => v.depart_id == createForm.depart_id)" :key="item.room_id" :label="item.room_name"
                            :value="item.room_id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="床号 ">
                    <el-input v-model="createForm.bed_name"></el-input>
                </el-form-item>
                <!-- <el-form-item label="状态">
                    <el-radio-group v-model="createForm.bed_state" class="ml-4">
                        <el-radio label="1" size="large">空床</el-radio>
                        <el-radio label="2" size="large">占用</el-radio>
                    </el-radio-group>
                </el-form-item> -->
                <el-form-item label="性质">
                    <el-radio-group v-model="createForm.bed_shape" class="ml-4">
                        <el-radio label="1" size="large">在编床</el-radio>
                        <el-radio label="2" size="large">非在编床(加床)</el-radio>
                        <el-radio label="3" size="large">虚床(家庭床)</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="床头屏SN">
                    <el-input v-model="createForm.screen_head_sn"></el-input>
                </el-form-item>
                <el-form-item label="床尾屏SN">
                    <el-input v-model="createForm.screen_foot_sn"></el-input>
                </el-form-item>
                <el-form-item label="床侧屏SN">
                    <el-input v-model="createForm.screen_side_sn"></el-input>
                </el-form-item>
                <el-form-item label="输液器SN">
                    <el-input v-model="createForm.infusion_sn"></el-input>
                </el-form-item>


                <!-- <el-form-item label="HIS对应ID">
                    <el-input v-model="createForm.bed_id_his"></el-input>
                </el-form-item> -->
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveCreate">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" v-model="editVisible" width="50%">
            <el-form label-width="110px">
                <el-form-item label="病区">
                    <el-select readonly v-model="eidtForm.info.depart_id" class="m-2" placeholder="请选择病区" size="large">
                        <el-option v-for="item in departs" :key="item.depart_id" :label="item.depart_name"
                            :value="item.depart_id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="房间">
                    <el-select readonly v-model="eidtForm.info.room_id" class="m-2" placeholder="请选择房间" size="large">
                        <el-option v-for="item in rooms.filter(v => v.depart_id == eidtForm.info.depart_id)" :key="item.room_id" :label="item.room_name"
                            :value="item.room_id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="床号 ">
                    <el-input v-model="eidtForm.info.bed_name"></el-input>
                </el-form-item>
                <!-- <el-form-item label="状态">
                    <el-radio-group v-model="eidtForm.info.bed_state" class="ml-4">
                        <el-radio label="1" size="large">空床</el-radio>
                        <el-radio label="2" size="large">占用</el-radio>
                    </el-radio-group>
                </el-form-item> -->
                <el-form-item label="性质">
                    <el-radio-group v-model="eidtForm.info.bed_shape" class="ml-4">
                        <el-radio label="1" size="large">在编床</el-radio>
                        <el-radio label="2" size="large">非在编床(加床)</el-radio>
                        <el-radio label="3" size="large">虚床(家庭床)</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="床头屏SN">
                    <el-input v-model="eidtForm.info.screen_head_sn"></el-input>
                </el-form-item>
                <el-form-item label="床尾屏SN">
                    <el-input v-model="eidtForm.info.screen_foot_sn"></el-input>
                </el-form-item>
                <el-form-item label="床侧屏SN">
                    <el-input v-model="eidtForm.info.screen_side_sn"></el-input>
                </el-form-item>
                <el-form-item label="输液器SN">
                    <el-input v-model="eidtForm.info.infusion_sn"></el-input>
                </el-form-item>

                <!-- <el-form-item label="HIS对应ID">
                    <el-input v-model="eidtForm.info.bed_id_his"></el-input>
                </el-form-item> -->
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveEdit">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 患者 -->
        <el-dialog title="床位患者" v-model="patientVisible" width="50%">
            <el-form label-width="110px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="病区">
                            <el-input readonly v-model="patientForm.info.depart_name"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="房间">
                            <el-input readonly v-model="patientForm.info.bed_room"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="病区">
                            <el-input readonly v-model="patientForm.info.depart_name"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="患者姓名">
                            <el-input v-model="patientForm.info.hz_name"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>

                    <el-col :span="12">
                        <el-form-item label="患者年龄">
                            <el-input v-model="patientForm.info.hz_age"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="患者性别">
                            <el-radio-group v-model="patientForm.info.hz_sex" class="ml-4">
                                <el-radio label="男" size="large">男</el-radio>
                                <el-radio label="女" size="large">女</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="住院号">
                            <el-input v-model="patientForm.info.hz_hop_no"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="入院时间">
                            <el-date-picker v-model="patientForm.info.hz_in_time" type="date" size="large"
                                value-format="YYYY-MM-DD" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="胸卡号">
                            <el-input v-model="patientForm.info.hz_badge"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="生日">
                            <el-date-picker v-model="patientForm.info.hz_birthdate" type="date" size="large"
                                value-format="YYYY-MM-DD" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="床位医生">
                            <el-select v-model="patientForm.info.hz_docter_id" class="m-2" placeholder="请选择床位医生"
                                size="large">
                                <el-option v-for="item in staffs" :key="item.staff_id" :label="item.staff_name"
                                    :value="item.staff_id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="责任护士">
                            <el-select v-model="patientForm.info.hz_nurse_id" class="m-2" placeholder="请选择责任护士"
                                size="large">
                                <el-option v-for="item in staffs" :key="item.staff_id" :label="item.staff_name"
                                    :value="item.staff_id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>


                <el-row>
                    <el-col :span="12">
                        <el-form-item label="诊断">
                            <el-input v-model="patientForm.info.hz_diagnosis"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="危重">
                            <el-radio-group v-model="patientForm.info.hz_isgrave" class="ml-4">
                                <el-radio label="0" size="large">非</el-radio>
                                <el-radio label="1" size="large">危重</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="护理等级">
                    <el-radio-group v-model="patientForm.info.hz_nurse_lever" class="ml-4">
                        <el-radio label="1" size="large">特级护理</el-radio>
                        <el-radio label="2" size="large">一级护理</el-radio>
                        <el-radio label="3" size="large">二级护理</el-radio>
                        <el-radio label="4" size="large">三级护理</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="过敏">
                    <el-input v-model="patientForm.info.hz_allergy"></el-input>
                </el-form-item>
                <el-form-item label="饮食">
                    <el-input v-model="patientForm.info.hz_diet"></el-input>
                </el-form-item>
                <el-form-item label="嘱托">
                    <el-input v-model="patientForm.info.hz_ntrust"></el-input>
                </el-form-item>
                <el-form-item label="特别交代">
                    <el-input v-model="patientForm.info.hz_account"></el-input>
                </el-form-item>

            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="patientVisible = false">取 消</el-button>
                    <el-button type="primary" @click="savePatient">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
    import { ref, reactive } from "vue";
    import { ElMessage, ElMessageBox } from "element-plus";
    import { staffAll, departAll, roomAll, bedList, bedCreate, bedUpdate, patientUpdate } from "../api/index";
    import { typeName, log, getUserInfo } from "../utils/user"

    export default {
        name: "basetable",
        setup() {
            const statusText = ["禁用", "启用"]
            const typeNames = typeName();

            let typeText = {};
            Object.keys(typeNames).forEach(k => {
                typeText[typeNames[k][0]] = typeNames[k][1]
            })
            log("typeText", typeText);

            const query = reactive({
                keywords: "",
                depart: '0',
                page: 1,
                limit: 15,
            });

            let user = getUserInfo();
            const departs = ref([]);

            const tableData = ref([]);
            const pageTotal = ref(0);

            // 获取表格数据
            const getData = () => {
                bedList(query).then((res) => {
                    if (res.status == 'ok') {
                        tableData.value = res.data.list.list;
                        pageTotal.value = res.data.list.pageTotal || 1;

                        if (departs.value.length == 0) {
                            if (user.is_admin == '0') {
                                let allDeparts = user.manage_departs ? user.manage_departs.split(',') : []
                                res.data.depart.forEach(depart => {
                                    if (allDeparts.indexOf(depart.depart_id + '') > -1) {
                                        departs.value.push(depart)
                                    }
                                })
                            } else {
                                departs.value = res.data.depart
                            }
                        }
                    } else {
                        ElMessage.error(res.msg)
                        return false;
                    }
                });
            };
            getData();

            // 查询操作
            const handleSearch = () => {
                query.page = 1;
                getData();
            };
            // 分页导航
            const handlePageChange = (val) => {
                query.page = val;
                getData();
            };

            // 删除操作
            const handleDelete = (index) => {
                // 二次确认删除
                ElMessageBox.confirm("确定要删除吗？", "提示", {
                    type: "warning",
                })
                    .then(() => {
                        ElMessage.success("删除成功");
                        tableData.value.splice(index, 1);
                    })
                    .catch(() => { });
            };
            const staffs = ref([]);
            const rooms = ref([]);
            // 表格添加
            const addVisible = ref(false);

            const handleCreate = () => {
                if (rooms.value.length == 0) {
                    roomAll({}).then(res => {
                        if (res.status == 'ok') {
                            rooms.value = res.data;
                            if (departs.value.length > 0) {
                                addVisible.value = true;
                            }
                        } else {
                            ElMessage.error(res.msg)
                            return false;
                        }
                    })
                }

                if (departs.value.length == 0) {
                    departAll({}).then(res => {
                        if (res.status == 'ok') {
                            departs.value = res.data;
                            if (rooms.value.length > 0) {
                                addVisible.value = true;
                            }
                        } else {
                            ElMessage.error(res.msg)
                            return false;
                        }
                    })
                }

                if (rooms.value.length > 0 && departs.value.length > 0) {
                    addVisible.value = true;
                }
            };
            let createForm = reactive({
                depart_id: "",
                room_id: '',
                bed_name: "",
                bed_state: "1",
                bed_shape: "1",
                bed_id_his: "",
                screen_head_sn: "",
                screen_foot_sn: "",
                screen_side_sn: "",
                infusion_sn: "",
            });

            const saveCreate = () => {
                log(createForm)
                if (!createForm.depart_id) {
                    ElMessage.error('请请选择病区')
                    return false;
                }
                if (!createForm.bed_name) {
                    ElMessage.error('请输入床号')
                    return false;
                }


                bedCreate(createForm).then(res => {
                    if (res.status == 'ok') {
                        addVisible.value = false;
                        ElMessage.success(res.msg);
                        query.pageIndex = 1;
                        getData();
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
            }


            // 表格编辑时弹窗和保存
            const editVisible = ref(false);
            let eidtForm = reactive({
                id: 0,
                type: 'edit',
                info: {
                    depart_id: "",
                    room_id: '',
                    bed_name: "",
                    bed_state: "",
                    bed_shape: "",
                    bed_id_his: "",
                    screen_head_sn: "",
                    screen_foot_sn: "",
                    screen_side_sn: "",
                    infusion_sn: "",
                }
            });
            let idx = -1;
            const handleEdit = (index, row) => {
                idx = index;
                eidtForm.info.depart_id = row["depart_id"];
                eidtForm.info.room_id = row["room_id"];
                eidtForm.info.bed_name = row["bed_name"];
                eidtForm.info.bed_state = row["bed_state"] + '';
                eidtForm.info.bed_shape = row["bed_shape"] + '';
                eidtForm.info.bed_id_his = row["bed_id_his"];
                eidtForm.info.screen_head_sn = row["screen_head_sn"];
                eidtForm.info.screen_foot_sn = row["screen_foot_sn"];
                eidtForm.info.screen_side_sn = row["screen_side_sn"];
                eidtForm.info.infusion_sn = row["infusion_sn"];

                eidtForm.id = row["bed_id"];
                log(eidtForm)
                if (rooms.value.length == 0) {
                    roomAll({}).then(res => {
                        if (res.status == 'ok') {
                            rooms.value = res.data;
                            if (departs.value.length > 0) {
                                editVisible.value = true;
                            }
                        } else {
                            ElMessage.error(res.msg)
                            return false;
                        }
                    })
                }

                if (departs.value.length == 0) {
                    departAll({}).then(res => {
                        if (res.status == 'ok') {
                            departs.value = res.data;
                            if (rooms.value.length > 0) {
                                editVisible.value = true;
                            }
                        } else {
                            ElMessage.error(res.msg)
                            return false;
                        }
                    })
                }

                if (rooms.value.length > 0 && departs.value.length > 0) {
                    editVisible.value = true;
                }
            };
            const saveEdit = () => {
                if (!eidtForm.info.depart_id) {
                    ElMessage.error('请请选择病区')
                    return false;
                }
                if (!eidtForm.info.bed_name) {
                    ElMessage.error('请输入床号')
                    return false;
                }


                bedUpdate(eidtForm).then(res => {
                    if (res.status == 'ok') {
                        editVisible.value = false;
                        ElMessage.success(res.msg);
                        getData();
                    } else {
                        ElMessage.error(res.msg)
                    }
                })

            };

            // 患者
            const patientVisible = ref(false);
            let patientForm = reactive({
                id: 0,
                info: {
                    depart_name: "",
                    bed_room: "",
                    bed_name: "",
                    hz_name: "",
                    hz_sex: "女",
                    hz_age: '',
                    hz_in_time: "",
                    hz_hop_no: "",
                    hz_badge: "",
                    hz_birthdate: "",
                    hz_docter_id: "",
                    hz_nurse_id: "",
                    hz_nurse_lever: "1",
                    hz_diagnosis: "",
                    hz_isgrave: "0",
                    hz_allergy: "",
                    hz_diet: "",
                    hz_ntrust: "",
                    hz_account: "",


                }
            });
            const handlePatient = (index, row) => {
                patientForm.info.depart_name = row["depart_name"];
                patientForm.info.bed_room = row["bed_room"];
                patientForm.info.bed_name = row["bed_name"];
                if (row['hz_name']) {
                    patientForm.info.hz_name = row["hz_name"];
                    patientForm.info.hz_sex = row["hz_sex"];
                    patientForm.info.hz_age = row["hz_age"];
                    patientForm.info.hz_in_time = row["hz_in_time"];
                    patientForm.info.hz_hop_no = row["hz_hop_no"];
                    patientForm.info.hz_birthdate = row["hz_birthdate"];
                    patientForm.info.hz_badge = row["hz_badge"];
                    patientForm.info.hz_docter_id = parseInt(row["hz_docter_id"]);
                    patientForm.info.hz_nurse_id = parseInt(row["hz_nurse_id"]);
                    patientForm.info.hz_nurse_lever = row["hz_nurse_lever"];
                    patientForm.info.hz_diagnosis = row["hz_diagnosis"];
                    patientForm.info.hz_isgrave = row["hz_isgrave"];
                    patientForm.info.hz_allergy = row["hz_allergy"];
                    patientForm.info.hz_diet = row["hz_diet"];
                    patientForm.info.hz_ntrust = row["hz_ntrust"];
                    patientForm.info.hz_account = row["hz_account"];
                }
                patientForm.id = row["bed_id"];

                if (staffs.value.length == 0) {
                    staffAll({}).then(res => {
                        if (res.status == 'ok') {
                            staffs.value = res.data;
                            if (departs.value.length > 0) {
                                patientVisible.value = true;
                            }
                        } else {
                            ElMessage.error(res.msg)
                            return false;
                        }
                    })
                }

                if (departs.value.length == 0) {
                    departAll({}).then(res => {
                        if (res.status == 'ok') {
                            departs.value = res.data;
                            if (staffs.value.length > 0) {
                                patientVisible.value = true;
                            }
                        } else {
                            ElMessage.error(res.msg)
                            return false;
                        }
                    })
                }

                if (staffs.value.length > 0 && departs.value.length > 0) {
                    patientVisible.value = true;
                }

            };
            const savePatient = () => {
                log(patientForm)
                if (!patientForm.info.hz_name) {
                    ElMessage.error('请输入患者姓名')
                    return false;
                }
                // if (!patientForm.info.hz_in_time) {
                //     ElMessage.error('请选择入院时间')
                //     return false;
                // }
                // if (!patientForm.info.hz_docter_id) {
                //     ElMessage.error('请选择床位医生')
                //     return false;
                // }
                // if (!patientForm.info.hz_nurse_id) {
                //     ElMessage.error('请选择责任护士')
                //     return false;
                // }

                patientUpdate(patientForm).then(res => {
                    if (res.status == 'ok') {
                        patientVisible.value = false;
                        ElMessage.success(res.msg);
                        getData();
                    } else {
                        ElMessage.error(res.msg)
                    }
                })

            };

            const toggleStatus = (id, status) => {
                log("toggleStatus", id)
                let temp = {
                    id: id,
                    info: {
                        status: status
                    }
                }

                ElMessageBox.confirm("确认修改吗", "提示", {
                    type: "warning",
                })
                    .then(() => {
                        accountUpdate(temp).then(res => {
                            if (res.status == 'ok') {
                                ElMessage.success(res.msg)
                                getData();
                                return false;
                            } else {
                                ElMessage.error(res.msg)
                                return false;
                            }
                        })
                    })
                    .catch(() => { });


            }
            const clearBed = (index, row) => {
                let temp = {
                    id: "0",
                    type: 'clear',
                    info: {
                        bed_state: 1
                    }
                }
                temp.id = row["bed_id"];

                bedUpdate(temp).then(res => {
                    if (res.status == 'ok') {
                        ElMessage.success('清床成功');
                        getData();
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
            }
            return {
                statusText,
                typeText,

                // data
                query,
                tableData,
                pageTotal,


                handleSearch,
                handlePageChange,
                handleDelete,

                editVisible,
                eidtForm,
                handleEdit,
                saveEdit,

                createForm,
                addVisible,
                handleCreate,
                saveCreate,

                toggleStatus,
                departs,
                rooms,

                patientVisible,
                patientForm,
                handlePatient,
                savePatient,
                staffs,
                clearBed
            };
        },
    };
</script>

<style scoped>
    .handle-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }

    .table {
        width: 100%;
        font-size: 14px;
    }

    .red {
        color: #ff0000;
    }

    .mr10 {
        margin-right: 10px;
    }

    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }

    .m-radio {
        margin: 12px;
    }
</style>